package com.csx.springcloud.loadbalancer.scl.integration.webClient;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.cloud.client.loadbalancer.reactive.ReactorLoadBalancerExchangeFilterFunction;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@RestController
public class WebClientSample {

    /**
     * 1. webClient 与 loadBalancer 结合使用
     */
    @Autowired
    private WebClient.Builder webClientBuilder;

    @GetMapping("/testWebClientWithLoadBalancer")
    public Mono<String> testWebClientWithLoadBalancer() {
        return webClientBuilder.build().get().uri("http://loadbalancer-demo:8001/test2")
                .retrieve().bodyToMono(String.class);
    }

    /**
     * 2. webClient 与 ReactorLoadBalancerExchangeFilterFunction 结合使用
     */
    @Autowired
    private ReactorLoadBalancerExchangeFilterFunction lbFunction;

    @GetMapping("/testWebClientWithReactorLoadBalancerExchangeFilterFunction")
    public Mono<String> doOtherStuff() {
        return WebClient.builder().baseUrl("http://loadbalancer-demo")
                .filter(lbFunction)
                .build()
                .get()
                .uri("/test2")
                .retrieve()
                .bodyToMono(String.class);
    }


    @GetMapping("/test2")
    public String test2() {
        return "test2";
    }
}